import { setToken, getToken, removeToken, setUser, getUser } from '@/utils/auth'
import { login, menu } from '@/api/user'
const state = () => ({
  token: getToken(),
  userInfo: getUser(),
  userMenu: []
})

const getters = {
}

const mutations = {
  async setToken(state, token) {
    state.token = token
    setToken(token)
  },
  setUserInfo(state, user) {
    state.userInfo = user
    setUser(user)
  },
  setMenu(state, list) {
    state.userMenu = list
  }
}
const actions = {
  async login(context, data) {
    const res = await login(data)
    const { token } = res.data.token
    const user = res.data.user
    // console.log(res)
    context.commit('setToken', token)
    context.commit('setUserInfo', user)
    setToken(token)
  },
  logout(context) {
    context.commit('setToken', '')
    removeToken()
    context.commit('setUserInfo', {})
  },
  async getMenu(context) {
    const res = await menu()
    // console.log(res)
    const list = res.data
    context.commit('setMenu', list)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
